import { createDeepSeek } from '@ai-sdk/deepseek';
import { streamText } from 'ai';
import { auth } from '@clerk/nextjs/server';
import { createMessage } from '@/db';
import { weatherTool } from '../chat-tools/weatherTool';
import { z } from 'zod'; // 导入 zod 库用于定义参数类型和验证输入数据

export const maxDuration = 30;

const deepseek = createDeepSeek({
  apiKey: process.env.DEEPAI_API_KEY,
  baseURL: process.env.BASE_URL,
})

export async function POST(req: Request) {
  const { messages, model, chat_id, chat_user_id } = await req.json();
  console.log("messages", messages)

  const { userId } = await auth()
  if (false) {
    return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 })
  }

  // 存入用户消息
  const lastMessage = messages[messages.length - 1]
  await createMessage(chat_id, lastMessage.content, lastMessage.role)

  const result = streamText({
    model: deepseek('deepseek-v3'),
    system: 'You are a helpful assistant.',
    messages,
    // tools: {
    //   weather: weatherTool,
    // },
    onFinish: async (result) => {
      await createMessage(chat_id, result.text, 'assistant')
    }
  })

  return result.toDataStreamResponse();
}